#import <Foundation/NSAutoreleasePool.h>
#import <stdlib.h>
#import <stdio.h>
#import <time.h>
#import "coordinationMiddleware.h"

//test de un objeto que soporta eventos
@interface TestObject : ListeningObject {
	int x;
	int y;
	EventHandler* handler;
}

-(id) initWithHandler:(EventHandler*)h;
-(void) changeValue:(int)x and:(int)y;

@end

@implementation TestObject

-(id) initWithHandler:(EventHandler*)h
{
	[super init];
	
	x = 0;
	y = 0;
	
	handler = h;
	
	return self;
}

-(void) changeValue:(int)xx and:(int)yy
{
	x = xx;
	y = yy;
	
	PairEvent* ev = [[PairEvent alloc] initWithCommunicator:[handler communicator]];
	[ev setX:x];
	[ev setY:y];
	
	[handler push:ev];
	
	[ev release];
}

@end


//test de una clase listener
@interface TestListener : NSObject <EventListener> {
	
}

@end

@implementation TestListener

-(BOOL) checkEvent:(Event*)evt
{
	if ([evt type] == PAIR_EVENT_TYPE)
		return YES;
		
	return NO;
}

-(void) action:(id)receiver event:(Event*)evt
{
	PairEvent* ev = [[PairEvent alloc] initWithEvent:evt];
	
	NSLog(@"recibido: %f, %f", [ev x], [ev y]);
	
	[ev release];
}

-(NSString*) name
{
	return @"test_listener";
}

@end


int main(int argc, char** argv)
{	
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	
	CoordinationMiddleware* collaborationSubsystem = [[CoordinationMiddleware alloc] init];
	if (collaborationSubsystem == nil)
	{
		NSLog(@"error al inicializar el sistema de colaboracion");
		exit(1);
	}
	
	//////////  TEST DE OBJETO EMISOR/RECEPTOR DE EVENTOS //////////
	TestObject* dobj = [[TestObject alloc] initWithHandler:[collaborationSubsystem eventHandler]];
	TestListener* listener = [[TestListener alloc] init];
	[dobj addEventListener:listener];
	
	[[collaborationSubsystem eventHandler] registerObject:dobj];
	
	NSLog(@"\n\nPrueba de componente distribuido:");
	float x,y;
	while(1){
		NSAutoreleasePool* pool2 = [[NSAutoreleasePool alloc] init];
		
		NSLog(@"introduzca numero para enviar evento: ");
		scanf("%f %f", &x, &y);
		
		[dobj changeValue:x and:y];
		
		[pool2 release];
	} //bucle infinito para evitar el fin del cliente
	
	[collaborationSubsystem release];
	[pool release];
	
	return 0;
}
